package boun.swe.bob.dao;

import boun.swe.bob.entities.Publication;
import boun.swe.bob.entities.User;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.stereotype.Component;

import java.sql.SQLException;
import java.util.List;

/**
 * This DAO corresponds to publications table in database
 */
@Component
public class PublicationDao extends GenericDaoImpl<Publication, Integer> {
    
    /**
     * This method is used for getting the publications of a user.
     *
     * @param userId the integer user id value to get the publications
     * @return the result set containing the publications
     */
    public List<Publication> getPublicationsByUserId(final Integer userId) {
    return (List<Publication>) hibernateTemplate.execute(new HibernateCallback() {
        public Object doInHibernate(Session session) throws HibernateException, SQLException {
            Query query = session.createSQLQuery("select * from publications p where (p.user_id = ?) order by publication_id desc").addEntity("p", Publication.class);
            query.setInteger(0, userId);
            return query.list();
        }
    });
    }
    /**
     * This method returns the publication record by specifying a publication id
     *
     * @param publicationId publication id
     * @return publication
     */
    public Publication getPublicationByPublicationId(final Integer publicationId) {
        return (Publication) hibernateTemplate.execute(new HibernateCallback() {
            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                Query query = session.createSQLQuery("select * from publications p where p.publication_id = ?").addEntity("p", Publication.class);
                query.setInteger(0, publicationId);
                return query.uniqueResult();
            }
        });
    }

    /**
     * This method is used for deleting a publication
     *
     * @param publicationId corresponds to publication ID in publications table
     */
    public void deletePublication(final int publicationId) {
        hibernateTemplate.execute(new HibernateCallback() {
            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                Query query = session.createSQLQuery("delete from publications where publication_id = ?");
                query.setInteger(0, publicationId);
                query.executeUpdate();
                return null;
            }
        });
    }
}